package com.ruoyi.project.beautyflower.order.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ruoyi.project.app.interfaces.BigDecimalHandleInterface;
import com.ruoyi.project.beautyflower.member.domain.Member;
import com.ruoyi.project.beautyflower.member.service.IMemberService;
import com.ruoyi.project.beautyflower.paymentHistory.domain.PaymentHistory;
import com.ruoyi.project.beautyflower.paymentHistory.service.IPaymentHistoryService;
import com.ruoyi.project.beautyflower.repaymentPlan.domain.RepaymentPlan;
import com.ruoyi.project.beautyflower.repaymentPlan.service.IRepaymentPlanService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.beautyflower.order.domain.Order;
import com.ruoyi.project.beautyflower.order.service.IOrderService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;

/**
 * 订单  信息操作处理
 *
 * @author lxs
 * @date 2018-10-15
 */
@Controller
@RequestMapping("/beautyflower/order")
public class OrderController extends BaseController implements BigDecimalHandleInterface {
    private String prefix = "beautyflower/order";

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IRepaymentPlanService repaymentPlanService;
    @Autowired
    private IPaymentHistoryService paymentHistoryService;

    @RequiresPermissions("beautyflower:order:view")
    @GetMapping()
    public String order() {
        return prefix + "/order";
    }

    /**
     * 查询订单 列表
     */
    @RequiresPermissions("beautyflower:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Order order) {
        startPage();
        List<Order> list = orderService.selectOrderList(order);
        return getDataTable(list);
    }

    /**
     * 新增订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存订单
     */
    @RequiresPermissions("beautyflower:order:add")
    @Log(title = "订单 ", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Order order) {
        return toAjax(orderService.insertOrder(order));
    }

    /**
     * 修改订单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        Order order = orderService.selectOrderById(id);
        mmap.put("order", order);
        return prefix + "/edit";
    }

    /**
     * 修改保存订单
     */
    @RequiresPermissions("beautyflower:order:edit")
    @Log(title = "订单 ", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Order order) {
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除订单
     */
    @RequiresPermissions("beautyflower:order:remove")
    @Log(title = "订单 ", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(orderService.deleteOrderByIds(ids));
    }

    /**
     * 订单详情
     */
    @GetMapping("/details/{id}")
    @RequiresPermissions("beautyflower:order:details")
    public String details(@PathVariable("id") Integer id, ModelMap mmap) {
        // 查询订单
        Order order = orderService.selectOrderById(id);
        mmap.put("order", order);

        // 查询下单人
        Member member = memberService.selectMemberById(order.getMemberId());
        mmap.put("member", member);

        // 查询计划
        RepaymentPlan repaymentPlan = new RepaymentPlan();
        repaymentPlan.setOrderNumber(order.getOrderNumber());
        List<RepaymentPlan> repaymentPlans = repaymentPlanService.selectList(repaymentPlan);
        mmap.put("plans", repaymentPlans);

        // 查询记录
        PaymentHistory paymentHistory = new PaymentHistory();
        paymentHistory.setOrderId(order.getOrderNumber());
        List<PaymentHistory> paymentHistories = paymentHistoryService.selectPaymentHistoryList(paymentHistory);
        mmap.put("histories", paymentHistories);

        return prefix + "/details";
    }

    /**
     * 修改订单
     */
    @GetMapping("/loandetails/{id}")
    public String loanDetails(@PathVariable("id") Integer id, ModelMap mmap) {
        // 查询订单
        Order order = orderService.selectOrderById(id);
        mmap.put("order", order);

        // 查询计划
        RepaymentPlan repaymentPlan = new RepaymentPlan();
        repaymentPlan.setOrderNumber(order.getOrderNumber());
        List<RepaymentPlan> repaymentPlans = repaymentPlanService.selectList(repaymentPlan);
        mmap.put("plans", repaymentPlans);

        // 计算已还款/待还款
        String amounting = "0";
        String amounted = "0";
        if (repaymentPlans != null) {
            for (RepaymentPlan plan : repaymentPlans) {
                if ("REPAID".equals(plan.getStatus())) {
                    if (plan.getDueInterestAmount() != null) {
                        amounted = handleAddStr(amounted, plan.getDueAmount().toString(), 2);
                    }
                } else {
                    if (plan.getDueInterestAmount() != null) {
                        amounting = handleAddStr(amounting, plan.getDueAmount().toString(), 2);
                    }
                }

            }
        }
        mmap.put("amounting", amounting);
        mmap.put("amounted", amounted);
        return prefix + "/loandetails";
    }

    /**
     * 修改订单
     */
    @GetMapping("/notice")
    public String notice(String id, String orderNumber, String memberId, ModelMap mmap) {
        List<RepaymentPlan> planList = repaymentPlanService.selectOrderByListByOrderNumber(orderNumber);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyyMMdd");
        String dateFormat = ymdFormat.format(new Date());

        // 计算还款金额
        String money = "0";
        // 计算本月还款金额
        String payMoney = "0";
        // 计算当前逾期总金额
        String overdueMoney = "0";
        // 计算逾期费用
        String overdueFee = "0";
        for (RepaymentPlan plan : planList) {
            if (plan != null && plan.getDueAmount() != null) {
                if (plan.getDueDate() != null && plan.getDueDate().length() == 8) {
                    String nowPayTime = dateFormat;
//                            + plan.getDueDate().substring(6);
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>nowPayTime=" + nowPayTime);
                    money = handleSubStr(money, plan.getDueAmount().toString(), 2);
                    if (Integer.valueOf(plan.getDueDate())>=Integer.valueOf(nowPayTime)) {
                        payMoney = handleSubStr(payMoney, plan.getDueAmount().toString(), 2);
                    } else {
                        overdueMoney = handleSubStr(overdueMoney, plan.getDueAmount().toString(), 2);
                        // 获取逾期天数
                        try {
                            int days = differentDays(ymdFormat.parse(nowPayTime), ymdFormat.parse(plan.getDueDate()));
                            overdueFee= handleSubStr(overdueFee, handleMulStr(String.valueOf(plan.getDueAmount()*0.001), String.valueOf(days), 2), 2);
                            money = handleSubStr(money,overdueFee, 2);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        // 计算按照逾期天数

                    }
                }
            }
        }

        mmap.put("orderId", id);
        mmap.put("orderNumber", orderNumber);
        mmap.put("memberId", memberId);
        mmap.put("money", money.replace("-",""));
        mmap.put("payMoney", payMoney.replace("-",""));
        mmap.put("overdueMoney", overdueMoney.replace("-",""));
        mmap.put("overdueFee", overdueFee.replace("-",""));
        return prefix + "/notice";
    }

    /**
     * date2比date1多的天数
     *
     * @param date1 Date
     * @param date2 Date
     * @return day
     */
    private int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        //是否同一年
        if (year1 != year2) {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                //是否闰年
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    timeDistance += 366;
                } else {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else {
            return day2 - day1;
        }
    }

    /**
     * 发送消息
     */
    @ResponseBody
    @PostMapping("/sendNotice")
    public AjaxResult sendNotice(Integer orderId, String memberId, String msg, String sms) {
        orderService.sendNotice(orderId, memberId, msg, sms);
        return success();
    }
}
